package com.smart.dao;

import com.smart.domain.Lesson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

@Repository // 通过spring注解定义一个Dao
public class LessonDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired // 自动注入jdbcTemplate 的bean
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    //插入


    public int  add( Lesson lesson) {

        final  String sql = "insert into lesson (name,starttime,stoptime,nickname) VALUES(?,?,?,?)";
        Object[] params= new Object[]{lesson.getName(),lesson.getStartTime(),lesson.getStopTime(),lesson.getNickName()};
        return jdbcTemplate.update(sql,params);
    }

 //删除lesson
    public int deletelesson(Lesson lesson){
        final String sql ="delete from lesson where name =?";
        return jdbcTemplate.update(sql,lesson.getName());
    }

    //修改lesson
    public int updatelesson(Lesson lesson){
        final String sqlt = "update lesson set name= ? ,starttime=? ,stoptime=?,nickname=? ";
        return jdbcTemplate.update(sqlt,lesson.getName(),lesson.getStartTime(),lesson.getStopTime(),lesson.getNickName());
    }
    //查询单个课程
    public void querylesson(Lesson lesson){
        String sql ="select * from lesson where name =?";
        Lesson com =jdbcTemplate.queryForObject(sql,new LeRowMapper(),lesson.getName());
        System.out.println(com);
    }
    public Lesson querylistCompRoom(){
        String sql ="select * from lesson";
        List<Lesson> com =jdbcTemplate.query(sql,new LeRowMapper());
        return (Lesson) com;
    }











}
class  LeRowMapper implements RowMapper<Lesson> {
    @Override
    public Lesson mapRow(ResultSet rs, int i) throws SQLException {
        //1 从结果集里得到数据

        String name=rs.getString("name");

        Date startTime =rs.getDate("starttime");
         Date stopTime=rs.getDate("stopTime");
        String nickName=rs.getString("nickName");

        //2 把得到数据封装到数据里面去
        Lesson com =new Lesson();
        com.setName(name);
        com.setStartTime(startTime);
        com.setStopTime(stopTime);
        com.setNickName(nickName);

        return com;
    }
}


